package tomcatDemo.version2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.print.attribute.HashAttributeSet;

public class TestServer {
	public static String WEB_ROOT = System.getProperty("user.dir")+"\\"+"WebContent";
	private static String url = "";
	//定义一个静态类型Map，存储服务端conf.properties中配置信息
	private static Map<String, String> map = new HashMap<>();
	static{
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(WEB_ROOT+"\\conf.properties"));
			Set set = properties.keySet();
			Iterator iterator = set.iterator();
			while(iterator.hasNext()){
				String key = (String) iterator.next();
				String value = properties.getProperty(key);
				map.put(key, value);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws IOException {
//		System.out.println(WEB_ROOT);
		System.out.println(map);
		ServerSocket serverSocket = null;
		InputStream is = null;
		OutputStream ops = null;
		Socket socket = null;
		try{
			serverSocket = new ServerSocket(8080);
			while(true){
				socket = serverSocket.accept();
				is = socket.getInputStream();
				
				ops = socket.getOutputStream();
				//获取HTTP协议的请求部分，截取客户端要访问的资源名称，将这个资源名称赋值给url
				parse(is);
				//判断请求是静态资源还是java小程序
				if(null != url){
					if(url.indexOf(".")!=-1){
						//发送静态资源
						sendStaticResource(ops);
					}else{
						//发送动态资源
						sendDynamicResource(is, ops);
					}
				}
				
				
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(null != is){
				is.close();
				is = null;
			}
			if(null != ops){
				ops.close();
				ops = null;
			}
			if(null != socket){
				socket.close();
				socket = null;
			}
		}
	}
	
	//发送动态资源
	private static void sendDynamicResource(InputStream is, OutputStream ops) throws Exception {
		// TODO Auto-generated method stub
		//将HTTP协议的响应行和响应头发送到客户端
		ops.write("HTTP/1.1 200 ok\n".getBytes());
		ops.write("Server:Apache\n".getBytes());
		ops.write("Content-Type:text/html;charset=utf-8\n".getBytes());
		ops.write("\n".getBytes());
		if(map.containsKey(url)){
			String value = map.get(url);
			Class clazz = Class.forName(value);
			Servlet servlet = (Servlet) clazz.newInstance();
			servlet.init();
			servlet.Service(is, ops);
		}
	}
	private static void sendStaticResource(OutputStream ops) throws IOException {
		// TODO Auto-generated method stub
		byte[] bytes = new byte[2048];
		FileInputStream fis = null;
		try{
			File file = new File(WEB_ROOT, url);
			if(file.exists()){
				ops.write("HTTP/1.1 200 OK\n".getBytes());
				ops.write("Server:apache-Coyote/1.1\n".getBytes());
				ops.write("Content-Type:text/html;charset=utf-8\n".getBytes());
				ops.write("\n".getBytes());
				fis = new FileInputStream(file);
				int ch = fis.read(bytes);
				while(ch!=-1){
					ops.write(bytes, 0, ch);
					ch = fis.read(bytes);
				}
			}else{
				ops.write("HTTP/1.1 404 not found\n".getBytes());
				ops.write("Server:apache-Coyote/1.1\n".getBytes());
				ops.write("Content-Type:text/html;charset=utf-8\n".getBytes());
				ops.write("\n".getBytes());
				String errorMessage = "file not found";
				ops.write(errorMessage.getBytes());
			}
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			if(null != fis){
				fis.close();
				fis = null;
			}
		}
	}
	private static void parse(InputStream is) throws IOException {
		// TODO Auto-generated method stub
		StringBuffer content = new StringBuffer();
		byte[] buffer = new byte[2048];
		int i = -1;
		i = is.read(buffer);
		for(int j=0; j<i; j++){
			content.append((char)buffer[j]);
		}
		parseUrl(content.toString());
	}
	private static void parseUrl(String content) {
		// TODO Auto-generated method stub
		int index1, index2;
		index1 = content.indexOf(" ");
		if(index1 != -1){
			index2 = content.indexOf(" ", index1+1);
			if(index2 > index1){
				url =  content.substring(index1+2, index2);
			}
		}
	}
}
